<template>
  <div class="erp-customer">
    <el-card shadow="never">
      <template #header>
        <div class="erp-customer__header">
          <span>客户管理</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="multipleSelection.length===0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="erp-customer__search" @submit.prevent>
        <el-form-item label="客户编码">
          <el-input v-model="query.code" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="query.name" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable>
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="tableRef" v-if="list.length > 0" :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="customerCode" label="客户编码" min-width="120" />
        <el-table-column prop="customerName" label="客户名称" min-width="160" />
        <el-table-column prop="contactPerson" label="联系人" min-width="100" />
        <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
        <el-table-column prop="contactAddress" label="联系地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="taxNumber" label="税号" min-width="120" />
        <el-table-column prop="bankName" label="开户银行" min-width="160" show-overflow-tooltip />
        <el-table-column prop="bankAccount" label="银行账号" min-width="160" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该客户？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无数据" />

      <div class="erp-customer__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-drawer v-model="drawerVisible" :with-header="true" :title="drawerTitle" size="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户编码" prop="customerCode">
          <el-input v-model="form.customerCode" maxlength="64" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" maxlength="200" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="form.contactPerson" maxlength="100" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.contactPhone" maxlength="50" />
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input v-model="form.contactAddress" type="textarea" :rows="2" maxlength="500" />
        </el-form-item>
        <el-form-item label="税号">
          <el-input v-model="form.taxNumber" maxlength="64" />
        </el-form-item>
        <el-form-item label="开户银行">
          <el-input v-model="form.bankName" maxlength="200" />
        </el-form-item>
        <el-form-item label="银行账号">
          <el-input v-model="form.bankAccount" maxlength="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" maxlength="500" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: 1; text-align: center">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { pageCustomer, getCustomer, createCustomer, updateCustomer, deleteCustomer, deleteCustomerBatch } from '@/api/erp/party'
import { ElMessage } from 'element-plus'
import type { CustomerDTO } from '@/api/erp/party'

const list = ref<any[]>([])
const tableRef = ref()
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{ code?: string; name?: string; status?: number | '' }>({ code: '', name: '', status: '' })
const multipleSelection = ref<any[]>([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增客户')
const formRef = ref<FormInstance>()
const form = reactive<CustomerDTO>({
  customerCode: '',
  customerName: '',
  contactPerson: '',
  contactPhone: '',
  contactAddress: '',
  taxNumber: '',
  bankName: '',
  bankAccount: '',
  status: 1,
  remark: ''
})
const rules: FormRules = {
  customerCode: [{ required: true, message: '请输入客户编码', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
}
const submitLoading = ref(false)

const load = async () => {
  const res = await pageCustomer({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    code: query.code || undefined,
    name: query.name || undefined,
    status: query.status === '' ? undefined : Number(query.status)
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.code = ''
  query.name = ''
  query.status = ''
  onSearch()
}

const resetForm = () => {
  form.customerId = undefined
  form.customerCode = ''
  form.customerName = ''
  form.contactPerson = ''
  form.contactPhone = ''
  form.contactAddress = ''
  form.taxNumber = ''
  form.bankName = ''
  form.bankAccount = ''
  form.status = 1
  form.remark = ''
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增客户'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑客户'
  const res = await getCustomer(String(row.customerId))
  const data = res?.data || {}
  form.customerId = String(data.customerId)
  form.customerCode = data.customerCode || ''
  form.customerName = data.customerName || ''
  form.contactPerson = data.contactPerson || ''
  form.contactPhone = data.contactPhone || ''
  form.contactAddress = data.contactAddress || ''
  form.taxNumber = data.taxNumber || ''
  form.bankName = data.bankName || ''
  form.bankAccount = data.bankAccount || ''
  form.status = Number(data.status ?? 1)
  form.remark = data.remark || ''
  drawerVisible.value = true
}

const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value && form.customerId) {
        await updateCustomer(String(form.customerId), {
          customerCode: form.customerCode,
          customerName: form.customerName,
          contactPerson: form.contactPerson,
          contactPhone: form.contactPhone,
          contactAddress: form.contactAddress,
          taxNumber: form.taxNumber,
          bankName: form.bankName,
          bankAccount: form.bankAccount,
          status: form.status,
          remark: form.remark
        })
      } else {
        await createCustomer({
          customerCode: form.customerCode,
          customerName: form.customerName,
          contactPerson: form.contactPerson,
          contactPhone: form.contactPhone,
          contactAddress: form.contactAddress,
          taxNumber: form.taxNumber,
          bankName: form.bankName,
          bankAccount: form.bankAccount,
          status: form.status,
          remark: form.remark
        })
      }
      drawerVisible.value = false
      ElMessage.success('保存成功')
      await load()
    } finally {
      submitLoading.value = false
    }
  })
}

const onDelete = async (row: any) => {
  await deleteCustomer(String(row.customerId))
  ElMessage.success('删除成功')
  await load()
}

const onSelectionChange = (rows: any[]) => {
  multipleSelection.value = rows
}

const onBatchDelete = async () => {
  if (multipleSelection.value.length === 0) return
  const ids = multipleSelection.value.map(it => String(it.customerId))
  await deleteCustomerBatch(ids)
  ElMessage.success('批量删除成功')
  await load()
}

onMounted(load)
</script>

<style scoped lang="scss">
.erp-customer {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__search {
    margin-bottom: 16px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

